/**
 * 神州信息(2013)
 */
/**
 * 神州信息(2013)
 */
package net.nextvisual.sheet.export;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.abbp.core.util.StringUtils;
import net.abbp.report.model.Cell;
import net.abbp.report.model.ReportModel;
import net.abbp.report.model.cell.style.HorizentalAlignment;
import net.abbp.report.model.cell.style.Style;

/**
 * Excel导出器
 * 
 * @version 1.0
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since 销售宝 2.0
 * 
 *        <pre>
 * 历史：
 *      建立: 2013-8-7 lexloo
 * </pre>
 */
public class XlsExport implements IExport {

    @Override
    public void export(ReportModel model, File file) {
        // 输出数据
        try {
            WritableCellFormat fLeft = new WritableCellFormat(NumberFormats.TEXT);
            fLeft.setBorder(Border.ALL, BorderLineStyle.THIN);
            fLeft.setVerticalAlignment(VerticalAlignment.CENTRE);
            fLeft.setAlignment(Alignment.LEFT);
            fLeft.setWrap(true);

            OutputStream os = new FileOutputStream(file);
            // 创建工作薄
            WritableWorkbook workbook = Workbook.createWorkbook(os);
            // 创建工作表
            final WritableSheet sheet = workbook.createSheet("报表", 0);

            for (int r = 0, rows = model.getRowCount(); r < rows; r++) {
                for (int c = 0, cols = model.getColumnCount(); c < cols; c++) {
                    Cell cell = model.getCell(c, r);
                    if (cell == Cell.EMPTY_CELL) {
                        continue;
                    } else {
                        if (cell.isMerged()) {
                            sheet.mergeCells(c, r, c + cell.getColumnSpan() - 1, r + cell.getRowSpan() - 1);
                        }
                        Style style = cell.getStyle();
                        HorizentalAlignment ha = style.getHorizentalAlignment();
                        
                        sheet.addCell(new Label(c, r, StringUtils.convertToString(cell.getValue()), fLeft));
                    }
                }
            }

            workbook.write();
            workbook.close();
            os.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
